package com.atguigu.bigdata.spark.core.wc

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
  * create by undeRdoG on  2021-06-06  14:54
  * 凡心所向，素履以往，生如逆旅，一苇以航。
  */
object Spark02_WordCount {

  def main(args: Array[String]): Unit = {

    val sparkConf = new SparkConf().setMaster("local").setAppName("WordCount")
    val sc = new SparkContext(sparkConf)


    val lines: RDD[String] = sc.textFile("datas")

    val words: RDD[String] = lines.flatMap(_.split(" "))

    val wordToOne: RDD[(String, Int)] = words.map(
      word => {
        (word, 1)
      }
    )

    val wordGroup: RDD[(String, Iterable[(String, Int)])] = wordToOne.groupBy(
      t => t._1
    )

    val wordTocount = wordGroup.map{
      case (word,list) => {
        list.reduce(
          (t1,t2) =>{
            (t1._1,t1._2 + t2._2)
          }
        )
      }
    }

    val array: Array[(String, Int)] = wordTocount.collect()

    array.foreach(println)
    sc.stop()
  }
}
